/*
 * @author: huangww
 * @Date: 2021-02-24 10:22:19
 * @LastEditTime: 2021-02-26 09:42:01
 * @FilePath: \fmgr\src\core\base\CmdBase.ts
 */
namespace core {
  export class CmdBase {
    /**
     * 事件回调字典
     */
    private _callbackMaps: Map<any, cmdItem>;

    public constructor() {
      this._callbackMaps = new Map<any, cmdItem>();
      // this._callbackMaps = {};
    }

    /**
     * 增加消息事件监听
     */
    addCmd(mode: number, action: string, func: Function, target: any, times: number = -1) {
      if (!this._callbackMaps.get(target)) {
        let eItem = {} as cmdItem;
        eItem.mode = mode;
        eItem.actions = [action];
        eItem.functions = [func];
        eItem.times = [times];
        this._callbackMaps.set(target, eItem);
      } else {
        this._callbackMaps.get(target).actions.push(action);
        this._callbackMaps.get(target).functions.push(func);
        this._callbackMaps.get(target).times.push(times);
      }
    }

    remove(target: any) {
      this._callbackMaps.delete(target);
    }

    /**自定义消息分发 */
    dispatch(mode: number, action, data?: any) {
      this._callbackMaps.forEach((value: cmdItem, key: any) => {
        for (let i = 0; i < value.actions.length; i++) {
          if (value.mode === mode && value.actions[i] === action) {
            value.functions[i].call(key, data);
            if (value.times[i] > 0) {
              value.times[i] -= 1;
              if (value.times[i] <= 0) {
                value.functions.splice(i, 1);
                value.actions.splice(i, 1);
                value.times.splice(i, 1);
              }
            }
            break;
          }
        }
        if (value.actions.length <= 0) {
          this._callbackMaps.delete(key);
        }
      })
    }

    clear() {
      this._callbackMaps.clear();
    }
  }

  export interface cmdItem {
    // obj : any;
    mode: number;
    actions: Array<string>;
    functions: Array<Function>;
    times: Array<number>;
  }
}